﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data;

namespace Server
{
    class AccountHandler : IHandler
    {
        public void Register(Dictionary<Protocal, Action<SocketClient ,ByteBuffer>> handers)
        {
            handers.Add(Protocal.Login_CMD, AccountLogin);
            handers.Add(Protocal.LogOut_CMD, AccountLogOut);
        }

        void AccountLogin(SocketClient client, ByteBuffer buffer)
        {
            ReqLogin req = ProtoHelper.Deserialize<ReqLogin>(buffer.ReadBytes());
            if (ActorManager.Instance.HasActor(req))
            {
                req.errorCode = new ErrorCode
                {
                    code = 0,
                    error = "您的账号或昵称已经登录游戏"
                };
                GameServer.Instance.SendClient(client, Protocal.Login_CMD, req);
            }
            else
            {
                //1.通知自己进入游戏/2/通知自己其他玩家
                ReqClient reqclient = new ReqClient();
                Random rand = new Random();
                //新玩家进入，初始化信息
                Account account = new Account
                {
                    username = req.username,
                    nickname = req.nickname,
                    point = rand.Next(0, 4),
                    hp = 5,
                    defaultHp = 5,
                    color = new Color
                    {
                        r = (float)rand.NextDouble(),
                        g = (float)rand.NextDouble(),
                        b = (float)rand.NextDouble(),
                    }
                };

                reqclient.errorCode = new ErrorCode
                {
                    code = 1,
                    error = "登录成功"
                };
                reqclient.localActor = account;
                LogManager.Log(req.username + "登录游戏：随机点：" + reqclient.localActor.point);
                reqclient.actors.AddRange(ActorManager.Instance.GetAllLogins());
                GameServer.Instance.SendClient(client, Protocal.Login_CMD, reqclient);

                //3.通知 其他 玩家自己进来
                GameServer.Instance.SendOther(client, Protocal.OtherLogin_CMD, account);

                //最后添加自己进actors
                ActorManager.Instance.Add(account, client);
            }
        }
        void AccountLogOut(SocketClient client, ByteBuffer buffer)
        {

        }
    }
}
